package com.greateffect.littlebud.lib.helper;

import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.util.Log;

/**
 * Created by ZengCS on 2019/8/16.
 * E-mail:zcs@sxw.cn
 * Add:成都市天府软件园E3-3F
 */
public class AutoPagerHelper {
    private static final String TAG = "AutoPagerHelper";
    private ViewPager viewPager;
    private int scrollState = ViewPager.SCROLL_STATE_IDLE;
    private Handler mHandler = new Handler();

    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            Log.d(TAG, "run() called scrollState = " + scrollState);
            if (viewPager == null) return;
            if (scrollState == ViewPager.SCROLL_STATE_IDLE) {
                viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);
            }
            // startAutoPage();
        }
    };

    public void setScrollState(int scrollState) {
        this.scrollState = scrollState;
        if (scrollState == ViewPager.SCROLL_STATE_IDLE) {
            startAutoPage();
        }
    }

    public AutoPagerHelper(ViewPager viewPager) {
        this.viewPager = viewPager;
    }

    public void startAutoPage() {
        mHandler.removeCallbacks(mRunnable);
        mHandler.postDelayed(mRunnable, 3_000);
    }

    public void stop() {
        if (mHandler != null)
            mHandler.removeCallbacks(mRunnable);
    }

    public void onPause() {
        stop();
    }

    public void onResume() {
        scrollState = ViewPager.SCROLL_STATE_IDLE;
        startAutoPage();
    }

    public void bindViewPager(ViewPager viewPager) {
        this.viewPager = viewPager;
    }
}
